//注意 createUser是异步函数
const { createUser, getUserInfo, getCurrentUser, updateAvatarService, updateUserDetailService, jobSubjectService ,userCountService} = require('../service/user.service')
const { userRegisterError } = require('../constant/err.type')
class UserController {
    async register(ctx, next) {
        // 1.获取数据
        const { username, password, email, phone } = ctx.request.body
        // 2.操作数据库
        try {
            // 调用service层最好加try catch
            const res = await createUser(username, password, email, phone)
            console.log(res)
            // 3.返回给客户端
            ctx.body = {
                data: res
            }
        } catch (err) {
            console.log(err)
            ctx.app.emit('error', userRegisterError, ctx)
        }

    }
    async login(ctx, next) {
        const { username } = ctx.request.body
        console.log(username, '🚀')
        // 获得用户信息
        const { is_admin, user_id } = await getUserInfo({ username })
        ctx.body = {
            status: 'ok',
            username,
            is_admin,
            user_id,
            // currentAuthority: 'admin'
        }
    }
    async currentUser(ctx, next) {

        const { user_id, username } = ctx.request.query
        console.log(user_id)
        const res = await getCurrentUser({ user_id: user_id, username: username })
        ctx.body = {
            code: 1000,
            data: res
        }

    }
    async getTest(ctx, next) {
        let temp = { data: 'get请求' }
        ctx.body = temp
    }
    async updateAvatar(ctx, next) {
        const { user_img, user_id } = ctx.request.body
        const res = await updateAvatarService({ user_img, user_id })
        ctx.body = {
            code: 1000,
            data: res
        }
    }
    async updateUserDetail(ctx, next) {
        const { phone = '', user_id, job = '', tag = '', email = '', signature = '', sex = 0 } = ctx.request.body
        const res = await updateUserDetailService({ phone, user_id, job, tag, email, signature, sex })
        ctx.body = {
            code: 1000,
            data: res
        }
    }
    async jobSubject(ctx, next) {
        const res = await jobSubjectService()
        ctx.body = {
            code: 1000,
            data: res
        }
    }
    async userCount(ctx,next){
        const res = await userCountService()
        ctx.body = {
            code: 1000,
            data: res
        }
    }

}

// 导出实例化的对象
module.exports = new UserController()